﻿using System;
using System.Diagnostics;
using System.Linq.Expressions;
using System.Web.Mvc;
using System.Web.Routing;
    
namespace Gama.Extension
{
    public static partial class HtmlHelperExtensions
    {
        public static ImageSubmitBuilder<TController> ImageSubmitEx<TController>(this HtmlHelper htmlHelper, Expression<Func<TController, ActionResult>> expression, string source)
            where TController : Controller
        {
            return new ImageSubmitBuilder<TController>(htmlHelper, expression, source);
        }
    }

    public class ImageSubmitBuilder<TController> : HtmlElementBuilder
        where TController : Controller
    {
        private readonly Expression<Func<TController, ActionResult>> expression;
        private readonly string imageUrl;
        private string alternateText;

        internal ImageSubmitBuilder(HtmlHelper htmlHelper, Expression<Func<TController, ActionResult>> expression, string source)
            : base(htmlHelper)
        {
            this.expression = expression;
            this.imageUrl = source;
        }

        public override string Build()
        {
            var body = this.expression.Body as MethodCallExpression;

            Debug.Assert(body != null); 

            // generate routes
            RouteValueDictionary routes = ControllerExtensions.CreateRoutes<TController>(body);

            // prepare url generator
            var urlHelper = new UrlHelper(this.htmlHelper.ViewContext.RequestContext);

            // create html element
            var anchor = new TagBuilder("input");

            anchor.MergeAttributes(new RouteValueDictionary(this.htmlAttributes));
            anchor.MergeAttribute("type","image");
            anchor.MergeAttribute("src", this.imageUrl);
            anchor.MergeAttribute("alt", this.alternateText);
            anchor.MergeAttribute("onClick", String.Format("javascript:return this.form.action='{0}';", urlHelper.Action(routes["action"].ToString(), routes["controller"].ToString(), routes)));
            
            return anchor.ToString();
        }

        public ImageSubmitBuilder<TController> AlternateText(string alternateText)
        {
            this.alternateText = alternateText;

            return this;
        }
    }    
}
